package com.finance.cooperate.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.framework.AdvisedSupport;
import org.springframework.aop.framework.AopProxy;
import org.springframework.aop.support.AopUtils;

import java.lang.reflect.Field;

/**
 * @ClassName AopTargetUtils
 * @Description 获取目标对象工具类，用过AOP注解后，获取的对象变成了代理对象
 * @Author shen
 * @Date 2022/10/20 16:48
 * @Modify ...
 */
@Slf4j
public class AopTargetUtils {

    /**
     * 获取 目标对象
     * @param proxy 代理对象
     * @return
     * @throws Exception
     */
    public static<T extends Object> T getTarget(T proxy) {

        try {

            if(!AopUtils.isAopProxy(proxy)) {
                return proxy;//不是代理对象
            }

            Object targetObject = null;
            if(AopUtils.isJdkDynamicProxy(proxy)) {

                targetObject = getJdkDynamicProxyTargetObject(proxy);

            } else { //cglib
                targetObject = getCglibProxyTargetObject(proxy);
            }

            return (T) targetObject;

        }catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }

        return null;
    }

    private static Object getCglibProxyTargetObject(Object proxy) throws Exception {
        Field h = proxy.getClass().getDeclaredField("CGLIB$CALLBACK_0");
        h.setAccessible(true);
        Object dynamicAdvisedInterceptor = h.get(proxy);

        Field advised = dynamicAdvisedInterceptor.getClass().getDeclaredField("advised");
        advised.setAccessible(true);

        return  ((AdvisedSupport)advised.get(dynamicAdvisedInterceptor)).getTargetSource().getTarget();
    }


    private static Object getJdkDynamicProxyTargetObject(Object proxy) throws Exception {
        Field h = proxy.getClass().getSuperclass().getDeclaredField("h");
        h.setAccessible(true);
        AopProxy aopProxy = (AopProxy) h.get(proxy);

        Field advised = aopProxy.getClass().getDeclaredField("advised");
        advised.setAccessible(true);

        return ((AdvisedSupport)advised.get(aopProxy)).getTargetSource().getTarget();
    }


}
